#include "userinfo.h"

Userinfo::Userinfo()
{
    db = QSqlDatabase::addDatabase("QSQLITE","sqlite1");
    db.setDatabaseName("info.db");
}

//建立数据库连接
bool Userinfo::createConnection()
{
    if(!db.open())
    {
        qDebug() << "无法建立数据库连接";
        return false;
    }
    qDebug()<<"数据库连接成功";
    return true;
}

//创建数据库表
bool Userinfo::createTable()
{
    QSqlQuery query(db);
    QString create_table = "create table users(id int primary key,name varchar,pwd varchar)";
    query.prepare(create_table);
    query.exec();
    return true;
}

//插入一条记录
bool Userinfo::insertData(int id , QString name ,QString pwd)
{
    QSqlQuery query(db);
    QString insertSql = "insert into users values(?,?,?)";
    query.prepare(insertSql);
    query.addBindValue(id);
    query.addBindValue(name);
    query.addBindValue(pwd);

    if(!query.exec())
    {
        qDebug()<<"插入失败";
        return false;
    }
    else
    {
        qDebug()<<"插入成功";
        return true;
    }
}

//检查账号密码是否存在
bool Userinfo::checkInfo(QString name, QString pwd)
{
    QSqlQuery query(db);
    QString selectSql = "select name, pwd from users";
    query.prepare(selectSql);
    qDebug() << "name = " << name;
    qDebug() << "passwd = " << pwd;
    if(!query.exec())
    {
        return false;
    }
    else
    {
        while(query.next())
        {
            QString name1 = query.value(0).toString();
            QString pwd1 = query.value(1).toString();
            qDebug() << "name1 = " << name1;
            qDebug() << "passwd1 = " << pwd1;
             if(name1 == name && pwd1 == pwd)
             {
                 return true;
             }
        }
    }
    return false;
}

//判断该id是否存在
bool Userinfo::selectUser(int id)
{
    QSqlQuery query(db);
    QString selectSql = "select * from users where id = ?";
    query.prepare(selectSql);
    query.addBindValue(id);
    if(!query.exec())
    {
        return false;
    }
    else
    {
        if(query.next())
        {
            return true;
        }
    }
    return false;
}

//关闭数据库
void Userinfo::closedb()
{
    db.close();
}


